package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(UserLoginDTO dto) {
        //httpclient构造登录凭证
        //请求参数构建
        Map<String, String> paramMap= new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", dto.getCode());
        paramMap.put("grant_type", "authorization_code");
        //发送请求
        String res =HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session",paramMap);
        log.info("微信登录返回结果：{}",res);

        //解析响应结果获取Openid
        JSONObject jsonObject=JSON.parseObject(res);
        String openid = (String) jsonObject.get("openid");
        if(openid==null){
            throw new RuntimeException("微信登录失败");
        }
        //判断新用户 opedid查user表
        User user = userMapper.selectByOpenid(openid);
        //新用户增到user表
        if (user==null){
             user =new User();
             user.setOpenid(openid);
             user.setCreateTime(LocalDateTime.now());
             user.setName(openid.substring(0,5));

             userMapper.insert(user);
        }
        return user;
    }
}
